/* global window */
import pathToRegexp from 'path-to-regexp'
import modelExtend from 'dva-model-extend'
import { config } from 'utils'
import * as basicData from 'services/basicData.js'
import * as customer from 'services/customer.js'
import * as account from 'services/accout.js'
import * as entity from 'services/entity.js'
import * as service from 'services/servicefee.js'
import * as exchangeRate from 'services/exchangerate.js'
import { combineReducers } from 'redux'
import { message } from 'antd'
import * as companyAccount from 'services/adminCompanyAccount.js'
import { create, remove, update, query,queryAll,report } from 'services/transactionReceipt/transactionReceiptDetail.js'
import { pageModel } from '../common'

export default modelExtend(pageModel, {
  namespace: 'transactionReportDetail',

  state: {
    customerData: [],
    formType: '',
    toType: '',
    customerId: '',
    customerAccount: [],
    customerEntity: [],
    toClients: [],
    fromClients: [],
    customerInfo: {},
    personId: '',
    companyAccount: [],
    currenciesTypeData: [],
    currenciesRateData: [],
    serviceAmountData: [],
    detailModalType: 'fromModal',
    entityVisible: false,
    accountVisible: false,
    showCustomerOperation: false,
    selectedRowKeys_from:[],
    selectedRowKeys_to:[],
    selectedRows_from:{},
    selectedRows_to:{},
    reportFromClient:{},
    reportToClient:{},
    CompfirmVisible:false,
  },

  subscriptions: {
    setup ({ dispatch, history }) {
      history.listen((pathname) => {
        const match = pathToRegexp('/transactionreport/detail/:ID').exec(pathname.pathname)
        if (match) {
          if (match[1] !== config.ADDFLAG) {
            dispatch({ type: 'query', payload: { id: match[1].slice(match[1].indexOf(':')+1,match[1].length) } })
            dispatch({type:'updateEditState',payload:{showCustomerOperation:true}})
          }
          dispatch({ type: 'iniBasicData' })
        }
      })
    },
  },

  effects: {
    * query ({ payload = {} }, { call, put }) {
      let sendData = {}
      sendData.id = payload.id
      const data = yield call(query, sendData)
      if (data.success) {
        yield put({
          type: 'updateEditState',
          payload: {
            editType: 'update',
            data: data.data,
            customerInfo:{
              customerNumber:data.data.customerNumber,
              middleName:data.data.middleName,
            },
            fromClients:data.data.fromClients,
            toClients:data.data.toClients,
          },
        })
      } else {
        throw data
      }
    },
    * delete ({ payload }, { call, put, select }) {
      const data = yield call(remove, { id: payload })
      const { selectedRowKeys } = yield select(_ => _.transactionReceiptDetail)
      if (data.success) {
        yield put({ type: 'updateState', payload: { selectedRowKeys: selectedRowKeys.filter(_ => _ !== payload) } })
        yield put({ type: 'query' })
        message.success('update success')
      } else {
        message.error('update failed')
        throw data
      }
    },

    * create ({ payload }, { call, put }) {
      const data = yield call(create, payload)
      if (data.success) {
        yield put({ type: 'query' })
        message.success('create success')
      } else {
        message.error('create failed')
        throw data
      }
    },

    * update ({ payload }, { select, call, put }) {
      const id = yield select(({ transactionReceiptDetail }) => transactionReceiptDetail.data.ID)
      const newReceipt = { ...payload, id }
      const data = yield call(update, newReceipt)
      if (data.success) {
        message.success('update success')
        yield put({ type: 'query' })
      } else {
        message.error('update failed')
        throw data
      }
    },

    * iniBasicData ({ payload = {} }, { call, put }) {
      yield put({ type: 'getCompanyAccount' })
      const currenciesData = yield call(basicData.listall, { type: 'Currencies' })
      const serviceAmount = yield call(service.allbrif, { type: 'listAll' })
      if (currenciesData.success) {
        yield put({
          type: 'updateState',
          payload: {
            currenciesTypeData: currenciesData.data,
            serviceAmountData: serviceAmount.data,
          },
        })
      }
    },

    * getCustomer ({ payload = {} }, { call, put }) {
      const customerRes = yield call(customer.listall, { ...payload })
      if (customerRes.success) {
        yield put({
          type: 'updateState',
          payload: {
            customerInfo: customerRes.data[0],
            personId: customerRes.data[0].personId,
            customerId: customerRes.data[0].id,
          },
        })
        yield put({ type: 'getCustomerAccount' })
        yield put({ type: 'getCustomerEntity' })
        yield put({
          type: 'updateState',
          payload: {
            showCustomerOperation: true,
          },
        })
      }
    },

    * getCustomerAccount ({ payload = {} }, { select, call, put }) {
      const { customerId } = yield select(_ => _.transactionReceiptDetail)
      payload.id = customerId
      const accountRes = yield call(account.list, { ...payload })
      let accountList = []
      accountRes.data.forEach(( value => {
        accountList.push({ accountId: value.id, name: value.accountName })
      }))
      if (accountRes.success) {
        yield put({
          type: 'updateState',
          payload: {
            customerAccount: accountList,
          },
        })
      }
    },

    * getCustomerEntity({ payload = {} }, { select, call, put }) {
      const { customerId } = yield select(_ => _.transactionReceiptDetail)
      payload.id = customerId
      const entityRes = yield call(entity.list, { ...payload})
      let entityList = []
      entityRes.data.forEach(( value => {
        entityList.push({ entityId: value.id, name: value.accountName })
      }))
      if (entityRes.success) {
        yield put({
          type: 'updateState',
          payload: {
            customerEntity: entityList,
          },
        })
      }
    },
    * saveAll ({ payload }, { call, put,select }) {
      const { reportFromClient } = yield select(_ => _.transactionReportDetail)
      const { reportToClient } = yield select(_ => _.transactionReportDetail)
      const payloadDataSorting = {
        amountLocal:payload.amountLocal,
        reportFromClient: {...reportFromClient,id:null},
        reportToClient: {...reportToClient,id:null},
        id: payload.id,
        fromAmountReport: reportFromClient.foreignAmount,
        toAmountReport: reportToClient.foreignAmount
      }
      let response = yield call(report, payloadDataSorting)
      if (response.success) {
        message.success('report success')
      } else {
        message.error('report failed')
      }
    },
    * getCompanyAccount({ payload = {} }, { call, put }) {
      const companyAccountRes = yield call(companyAccount.listall)
      let companyAccountList = []
      companyAccountRes.data.forEach(( value => {
        companyAccountList.push({ companyAccountId: value.id, name: value.name })
      }))
      if (companyAccountRes.success) {
        yield put({
          type: 'updateState',
          payload: {
            companyAccount: companyAccountList,
          },
        })
      }
    },
    * getCurrencyRate({ payload }, { call, put }) {
      const currenciesData = yield call(exchangeRate.currency, { ...payload })
      if (currenciesData.success) {
        currenciesData.data.key = currenciesData.data.id
        //一个对象转换为数组后放进数组里 [[]]
        var tempArr = [];
        tempArr[0] = currenciesData.data;
        yield put({
          type: 'updateState',
          payload: {
            currenciesRateData: tempArr
          },
        })
      }
    },
    * showModal ({ payload }, { put }) {
      yield put({
        type: 'updateModalState',
        payload: { ...payload },
      })
    },
    * deletelocal ({ payload }, { put }) {
      const { currentItem, arr, arrname } = payload
      const deleteId = currentItem.index
      const list = arr.filter(item => item.index !== deleteId)
      let kv = {}
      kv[arrname] = list
      yield put({
        type: 'updateState',
        payload: kv,
      })
    },
  },

  reducers: {
    updateSelectState (state, { payload }) {
      return { ...state, ...payload }
    },

    updateEditState (state, { payload }) {
      return { ...state, ...payload }
    },
    updateComfirmModal (state, { payload }) {
      return { ...state, ...payload }
    },
    //按下ok 修改数据并关闭dialog
    updateModal (state, { payload }) {
      var commitData = {}
      const clientType = (state.detailModalType == 'fromModal' )? 'fromClients' : 'toClients'
      const _clientType = (state.detailModalType == 'fromModal' )? 'reportFromClient' : 'reportToClient'
      if (state.modalType === 'update') {
        state[_clientType] = state[clientType].filter(item => item.id === state.currentItem.id)
        state[clientType] = state[clientType].filter(item => item.id !== state.currentItem.id)
      }
      state[_clientType] = {...state[_clientType][0],...payload}
      commitData[clientType] = state[clientType].concat(state[_clientType])//将字符串转为数组
      return {
        ...state,
        ...commitData,
        selectedRowKeys_from:[],
        selectedRowKeys_to:[],
        modalVisible: false,
        CompfirmVisible:false,
      }
    },
  },
})
